#include "stdint.h"
#include "stdio.h"
#include "DevicesADC.h"


__aligned(4) static uint16_t st_usADCDmaDatas[ADC0_SAMPLING_NUMBER][ADC0_SAMPLING_CHANNEL] = {0};


void vADCInit(void)
{
    // adc1_config_width(ADC_WIDTH_BIT_12);

    // adc1_config_channel_atten(ADC1_CHANNEL_0, ADC_ATTEN_DB_0);
}

/*!
    \brief      ADC dma channel
    \param[in]  none
    \param[out] none
    \retval     none
*/
float fADCGetDMAValue(AdcDmaChannelEnum enumChannel)
{
#if (ADC0_SAMPLING_NUMBER < 3)
    return ((int32_t)st_usADCDmaDatas[0][enumChannel] * (3.3f / 4095.0f));

#else
    uint32_t uiValueSum = 0;
    uint16_t *pDatasHand = &st_usADCDmaDatas[0][enumChannel];
    uint16_t usValueMax = 0, usValueMin = 0xFFFF, usValueNow, i;

    if(enumChannel > ADC0_SAMPLING_CHANNEL)
        return 0.0f;

    for(i = 0; i < ADC0_SAMPLING_NUMBER; ++i, pDatasHand += ADC0_SAMPLING_CHANNEL)
    {
        usValueNow  = *pDatasHand;
        uiValueSum += usValueNow;

        /* 找到最大与最小值 */
        usValueMax = (usValueMax < usValueNow) ? usValueNow : usValueMax;
        usValueMin = (usValueMin > usValueNow) ? usValueNow : usValueMin;
    }

    uiValueSum -= usValueMax + usValueMin;

    return ((float)uiValueSum / (ADC0_SAMPLING_NUMBER - 2) * (3.3f / 4095.0f));

#endif
}

/*!
    \brief      ADC channel sample
    \param[in]  none
    \param[out] none
    \retval     none
*/
float fADCGetChannelValue(uint8_t channel, uint32_t uiCnt)
{
    uint32_t uiValueSum = 0, i;
    uint16_t usValueMax = 0, usValueMin = 0xFFFF, usValueNow;

    /* 切换通道后，丢弃第一次转换的数据 */
    adc1_get_raw(channel);

    for(i = 0; i < uiCnt; ++i)
    {
        usValueNow = adc1_get_raw(channel);
        uiValueSum += usValueNow;;

        /* 找到最大与最小值 */
        usValueMax = (usValueMax < usValueNow) ? usValueNow : usValueMax;
        usValueMin = (usValueMin > usValueNow) ? usValueNow : usValueMin;
    }

    /* 去除最大与最小值 */
    uiValueSum -= (usValueMax + usValueMin);

    return ((float)uiValueSum / (uiCnt - 2) * (3.3f / 4095.0f));
}
